package com.diqye.db.sql;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.io.IOUtils;

import com.diqye.db.exception.XException;
import com.diqye.log.Logger;

public class DiqyeSqlFileLoader implements SqlLoader {

	public Map<String,String> sqlmap = new HashMap<String, String>();
	public String encoding="UTF-8";
	private Logger log = Logger.getLogger(getClass());
	
	@Override
	public String getSql(String id) {
		return sqlmap.get(id);
	}
	public void loadFile(String path){
		loadFile(new File(path));
	}
	public void loadFile(File pathFile){
		FileInputStream is = null;
		String sqlstr;
		try {
			is = new FileInputStream(pathFile);
			sqlstr = IOUtils.toString(is, encoding);
		} catch (IOException e) {
			throw new RuntimeException(e);
		}finally{
			try {
				if(is !=null)is.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		sqlstr=sqlstr
		  		.replaceAll("\r\n", "\n")
		  		.replaceAll("/(?ms)\\*.*\\*/", "")
				.replaceAll("\r", "\n")
				.replaceAll("--.*\n", "\n")
				.replaceAll("\t\n", "\n")
				.replaceAll("  \n", "\n")
				.replaceAll(" \n", "\n");
		boolean noteof=true;
		int searindex=0,lastindex=0,i1;
		String key=null,value=null,s1;
		while((searindex=sqlstr.indexOf(":\n", lastindex))!=-1||noteof){
			if(searindex==-1){
				searindex=sqlstr.length();
				noteof=false;
			}
			s1=sqlstr.substring(lastindex, searindex);
			if(lastindex==0){
				key=s1;
			}else{
				if(noteof)i1=s1.lastIndexOf("\n");
				else i1=s1.length();
				if(i1==-1)value=null;
				value=s1.substring(0, i1);
				if(value!=null&&!"".equals(value)){
					sqlmap.put(key.trim(), value);
				}
				key=s1.substring(i1);
			}
			lastindex=searindex+2;
		}
		
	}
	
	public DiqyeSqlFileLoader san(String suffix){
		log.info("扫描编译后的目录");
		URL pathurl=this.getClass().getResource("/");
		File pathDir=null;
		try {
			pathDir=new File(pathurl.toURI());
		} catch (URISyntaxException e) {
			throw new XException("",e);
		}
		eachFile(pathDir,suffix);
		log.info("扫描结束");
		return this;
	}
	
	public void eachFile(File dir,String suffix){
		File[] fs = dir.listFiles();
		for(File f:fs){
			if(f.isDirectory()){
				eachFile(f, suffix);
				continue;
			}
			if(f.getName().endsWith(suffix)){
				log.debug("加载文件文件:"+f.getAbsolutePath());
				loadFile(f);
			}
		}
	}
	

}
